package cn.wolfcode.luowowo.comment.service.impl;


import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository travelCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    public TravelComment save(TravelComment travelComment) {
        travelComment.setCreateTime(new Date());
        if(travelComment.getType()==TravelComment.TRAVLE_COMMENT_TYPE){
            //找到关联的评论然后存到普通评论中
            TravelComment travelComment2 = travelCommentRepository.findById(travelComment.getRefComment().getId()).get();
            travelComment.setRefComment(travelComment2);
        }
        return travelCommentRepository.save(travelComment);
    }
    public Long getCount(Long travelId) {
        Query query = new Query();
        if(travelId!=-1){
            query.addCriteria(Criteria.where("travelId").is(travelId));
        }
        long count = mongoTemplate.count(query, TravelComment.class);
        return count;
    }

    public List<TravelComment> list(Long tid) {
        Query query= new Query();
        query.addCriteria(Criteria.where("travelId").is(tid));
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return list;
    }

    public Page query(TravelCommentQuery qo) {
        Query query = new Query();
        //Criteria criteria = new Criteria("detailId").is(qo.getDetailId());
        //Criteria.where("detailId") =new Criteria(detailId)
        //注意这里的page当前页是从0开始的
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        //查询总条数
        long count = mongoTemplate.count(query, TravelComment.class);
        query.with(pageable);
        //查询当前显示数据集合
        if(qo.getTravelId()!=-1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        List<TravelComment> travelComments = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl(travelComments,pageable,count);
    }



}
